
package com.college.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.college.constant.SystemConstant;
import com.college.entity.User;



/**
 * 
 * 管理过滤器
 * 
 * @author bob
 * 
 */
public class AdminFilter implements Filter {

	protected final Logger logger = Logger.getLogger(this.getClass());

	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest servletRequest,
			ServletResponse servletResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		User user =  (User) request.getSession().getAttribute(
				SystemConstant.SESSION_USER);
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://"
				+ request.getServerName() + ":" + request.getServerPort()
				+ path;
		String forwardUrl = null;
		String uri = request.getRequestURI();
		if (user == null) {
			response.sendRedirect(basePath + "/auth/login.htm");
		}else if(user != null && user.getClassIdList() == null &&  "STUDENT".endsWith(user.getRoleType().toString()) ){
			
			if(!request.getRequestURI().contains("joinClassPage.htm") && !uri.contains("joinClasses.json")){
				forwardUrl = "/user/student/joinClassPage.htm";
				logger.info("Interceptor：跳转到加入班级的页面！");  
			    response.sendRedirect(basePath + forwardUrl);
			}else{
				chain.doFilter(request, response);
			}
				/*else if("TEACHER".endsWith(user.getRoleType().toString())){
			}
				forwardUrl = "/user/teacher/classCourseManage.htm";
			}else if("STUADMIN".endsWith(user.getRoleType().toString())){
				forwardUrl = "student/pages/joinClassPage.ftl";
			}*/
			
		}else if(user != null && user.getClassIdList() == null && !request.getRequestURI().contains("classCourseManage.htm") && !uri.contains("joinClasses.json")){ 
			if("TEACHER".endsWith(user.getRoleType().toString())){
				forwardUrl = "/user/teacher/classCourseManage.htm";
				response.sendRedirect(basePath + forwardUrl);
			}
		}else {
			chain.doFilter(request, response);
		}
	}

	public void destroy() {
		// TODO Auto-generated method stub

	}

}
